package com.huai.jt1078.handler.http;

import com.huai.jt1078.entity.Session;
import com.huai.jt1078.utils.ByteUtil;
import com.huai.jt1078.utils.FileUtils;
import com.huai.jt1078.utils.SessionManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.AttributeKey;

import java.io.File;

/**
 * @author xingkong
 * @program jt1078
 * @description
 * @date 2021-09-09 00:46
 **/
public class NettyHttpServerHandler extends ChannelInboundHandlerAdapter {

    private static final String VIDEO_PATH = "/video/";
    private static final String HEADER_ENCODING = "ISO-8859-1";

    private static final AttributeKey<Session> SESSION_KEY = AttributeKey.valueOf("session");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fhr = (FullHttpRequest) msg;
        String uri = fhr.uri();
        if (uri.startsWith(VIDEO_PATH)){
            String tag = uri.substring(VIDEO_PATH.length());
           // System.out.println(uri);
            ByteBuf buffer = ctx.alloc().buffer();

            buffer.writeBytes("HTTP/1.1 200 OK\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Connection: keep-alive\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Content-Type: video/x-flv\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Transfer-Encoding: chunked\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Cache-Control: no-cache\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Access-Control-Allow-Origin: *\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("Access-Control-Allow-Credentials: true\r\n".getBytes(HEADER_ENCODING));
            buffer.writeBytes("\r\n".getBytes(HEADER_ENCODING));

            ctx.writeAndFlush(ByteUtil.readReadableBytes(buffer)).await();

            SessionManager.instance.getTargetTagChannelMap().put(tag,ctx);
            // 注册视频通道
        }else if (uri.equals("/test/multimedia")){
            responseHTMLFile("static/multimedia.html", ctx);
        }
    }

    public final void setSession(ChannelHandlerContext context, Session session) {
        context.channel().attr(SESSION_KEY).set(session);
    }

    private void responseHTMLFile(String htmlFilePath, ChannelHandlerContext ctx)
    {
        byte[] fileData = FileUtils.read(new File("D:\\house\\jtt1078\\src\\main\\resources\\multimedia.html"));
        ByteBuf body = Unpooled.buffer(fileData.length);
        body.writeBytes(fileData);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(200), body);
        response.headers().add("Content-Length", fileData.length);
        ctx.write(response);
        ctx.flush();
    }
}
